package com.xrz.sxm.aj.view;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xrz.sxm.aj.activity.R;
import com.xrz.sxm.aj.utils.DisplayUtil;

public class FenKeViewGroup extends LinearLayout {

	private LayoutInflater m_Inflater;

	public FenKeViewGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public FenKeViewGroup(Context context) {
		super(context);
		init();
	}

	private void init() {
		setPadding(3, 3, 3, 6);
		setOrientation(HORIZONTAL);
		setGravity(Gravity.CENTER_VERTICAL);
		setBackgroundResource(R.mipmap.status_bak);
		m_Inflater = LayoutInflater.from(getContext());
		this.addView(createBtn("科目", false));
	}


	/** 生成分隔符 */
	private TextView createSplit() {
		TextView tv = new TextView(getContext());
		tv.setTextSize(DisplayUtil.sp2px(getContext(), 10));
		tv.setTextColor(Color.WHITE);
		tv.setText("----");
		return tv;
	}

	private TextView createBtn(String text, boolean isChecked) {
		final TextView rb = new TextView(getContext());
		rb.setText(text);
		rb.setGravity(Gravity.CENTER);
		rb.setPadding(5, 0, 5, 2);
		rb.setTextSize(18);
		rb.setTextColor(Color.WHITE);
		setChecked(rb, isChecked);
		rb.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				boolean tag = (Boolean) arg0.getTag();
				if (tag) {
					return;
				}
				if(listener != null)
					listener.onTitleItemClick(rb.getText().toString());
				setChecked(arg0, true);
				reset(arg0);
			}
		});
		return rb;
	}

	private void reset(View view) {
		int count = this.getChildCount();
		int index = this.indexOfChild(view);
		for (int i = index + 1; i < count; i++) {
			this.removeViewAt(this.getChildCount() - 1);
			postInvalidate();
		}
	}

	private void clearChecked() {
		for (int i = 0; i < this.getChildCount(); i++) {
			TextView view = (TextView) this.getChildAt(i);
			if (view.getText().toString().equals("---") == false) {
				setChecked(view, false);
			}
		}
	}

	public void addItem(String text) {
		clearChecked();
		this.addView(createSplit());
		this.addView(createBtn(text, true));
	}

	private void setChecked(View viwe, boolean isChecked) {
		viwe.setTag(isChecked);
		viwe.setBackgroundResource(isChecked ? R.mipmap.btn_checked
				: R.mipmap.btn_nomal);
	}

	public interface OnTitlteItemClickListener{
		void onTitleItemClick(String clickText);
	}

	private OnTitlteItemClickListener listener;
	public void setOnTitlteItemClickListener(OnTitlteItemClickListener listener){
		this.listener = listener;
	}

}
